package cn.wenhe9.novel.manager;

import cn.wenhe9.novel.constant.CacheConsts;
import cn.wenhe9.novel.constant.DatabaseConsts;
import cn.wenhe9.novel.domain.dto.UserBookShelfDto;
import cn.wenhe9.novel.domain.dto.UserFeedbackDto;
import cn.wenhe9.novel.domain.entity.user.UserBookshelf;
import cn.wenhe9.novel.domain.entity.user.UserFeedback;
import cn.wenhe9.novel.mapper.UserBookshelfMapper;
import cn.wenhe9.novel.mapper.UserFeedbackMapper;
import cn.wenhe9.novel.result.PageResultDto;
import cn.wenhe9.novel.result.ResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DuJinliang
 * 2022/5/27
 */
@Component
public class UserBookShelfCacheManager {
    @Resource
    private UserBookshelfMapper userBookshelfMapper;

    /**
     * 查询用户信息，并放入缓存中
     */
    @Cacheable(
            value = CacheConsts.USER_BOOKSHELF_CACHE_NAME,
            cacheManager = CacheConsts.REDIS_CACHE_MANAGER
//            keyGenerator = "keyGenerator"
    )
    public PageResultDto<UserBookShelfDto> listBookShelf(Long userId, Long page, Long limit) {
        Page<UserBookShelfDto> bookShelfDtoPage = userBookshelfMapper.queryBookshelfByPage(new Page<>(page, limit), userId);
        return PageResultDto.of(page, limit, bookShelfDtoPage.getTotal(), bookShelfDtoPage.getRecords());
    }


    @CacheEvict(
            value = CacheConsts.USER_BOOKSHELF_CACHE_NAME,
            cacheManager = CacheConsts.REDIS_CACHE_MANAGER,
            allEntries = true
    )
    public void addToBookShelf(Long userId, Long bookId, Long preContentId) {
        UserBookshelf userBookshelf = new UserBookshelf();
        userBookshelf.setUserId(userId);
        userBookshelf.setBookId(bookId);
        userBookshelf.setPreContentId(preContentId);
        userBookshelf.setCreateTime(LocalDateTime.now());
        userBookshelf.setUpdateTime(LocalDateTime.now());

        userBookshelfMapper.insert(userBookshelf);
    }

    @CacheEvict(
            value = CacheConsts.USER_BOOKSHELF_CACHE_NAME,
            cacheManager = CacheConsts.REDIS_CACHE_MANAGER,
            allEntries = true
    )
    public ResultResponse<Void> removeFromBookShelf(Long userId, Long bookId) {
        QueryWrapper<UserBookshelf> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConsts.UserBookshelfTable.COLUMN_USER_ID, userId);
        queryWrapper.eq(DatabaseConsts.UserBookshelfTable.COLUMN_BOOK_ID, bookId);
        userBookshelfMapper.delete(queryWrapper);
        return ResultResponse.ok();
    }
}
